package com.atguigu.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.app.func.BeanToJsonStrFunction;
import com.atguigu.edu.realtime.bean.UserRegister;
import com.atguigu.edu.realtime.util.DateFormatUtil;
import com.atguigu.edu.realtime.util.DorisUtil;
import com.atguigu.edu.realtime.util.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * 各窗口注册用户数
 */
public class dwsUserUserRegisterWindow {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(1, Time.seconds(1)));
        //从kafka读数据
        String topic = "dwd_user_register";
        String groupId = "dws_user_info_num";
        KafkaSource<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);
        DataStreamSource<String> kafkaDs = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafka_source");
        //转化，id分组，状态过滤去重，后才可以有水位线
        SingleOutputStreamOperator<JSONObject> jsonObjDs = kafkaDs.map(new MapFunction<String, JSONObject>() {
                    @Override
                    public JSONObject map(String value) throws Exception {
                        return JSON.parseObject(value);
                    }
                })
                .keyBy(value -> value.getString("id"))
                .process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {
                    private ValueState<JSONObject> valueState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<JSONObject> stateDescriptor = new ValueStateDescriptor<JSONObject>("valueState", JSONObject.class);
                        stateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.days(1)).build());
                        valueState = getRuntimeContext().getState(stateDescriptor);
                    }

                    @Override
                    public void processElement(JSONObject value, KeyedProcessFunction<String, JSONObject, JSONObject>.Context ctx, Collector<JSONObject> out) throws Exception {
                        JSONObject jsonObject = valueState.value();
                        if (jsonObject == null) {
                            valueState.update(value);
                            long ts = ctx.timerService().currentProcessingTime();
                            ctx.timerService().registerProcessingTimeTimer(ts+5000L);
                        }else{
                            String ar = jsonObject.getString("ar");
                            if(ar == null){
                                valueState.update(value);
                            }
                        }
                    }

                    @Override
                    public void onTimer(long timestamp, KeyedProcessFunction<String, JSONObject, JSONObject>.OnTimerContext ctx, Collector<JSONObject> out) throws Exception {
                        out.collect(valueState.value());
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<JSONObject>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                                    @Override
                                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                                        return element.getLong("ts") * 1000;
                                    }
                                })
                );
        //转化成对象
        SingleOutputStreamOperator<UserRegister> userDs = jsonObjDs.process(new ProcessFunction<JSONObject, UserRegister>() {
            @Override
            public void processElement(JSONObject value, ProcessFunction<JSONObject, UserRegister>.Context ctx, Collector<UserRegister> out) throws Exception {
                UserRegister userRegister = new UserRegister("", "", "", 1L);
                out.collect(userRegister);
            }
        });
        //开窗，求注册数
        SingleOutputStreamOperator<UserRegister> reduceDs = userDs.windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
                .reduce(new ReduceFunction<UserRegister>() {
                    private Long count = 0L;

                    @Override
                    public UserRegister reduce(UserRegister value1, UserRegister value2) throws Exception {
                        count++;
                        value1.setRCt(count);
                        return value1;
                    }
                }, new AllWindowFunction<UserRegister, UserRegister, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<UserRegister> values, Collector<UserRegister> out) throws Exception {
                        String stt = DateFormatUtil.toYmdHms(window.getStart());
                        String edt = DateFormatUtil.toYmdHms(window.getEnd());
                        String curDate = DateFormatUtil.toDate(window.getStart());
                        for (UserRegister value : values) {
                            value.setStt(stt);
                            value.setEdt(edt);
                            value.setCurDate(curDate);
                            out.collect(value);
                        }
                    }
                });
        reduceDs.print();
        //将聚合结果写到Doris中
        reduceDs.map(new BeanToJsonStrFunction<>())
                .sinkTo(DorisUtil.getDorisSink("dws_user_user_register_window"));

        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
